/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package com.github.florent37.camerafragment.sample;

import ohos.aafwk.ability.fraction.FractionAbility;
import ohos.aafwk.content.Intent;
import ohos.bundle.IBundleManager;

import com.github.florent37.camerafragment.internal.utils.Toast;
import com.github.florent37.camerafragment.sample.bean.RxBusEvent;
import com.github.florent37.camerafragment.sample.rxbus.RxBus;
import com.github.florent37.camerafragment.sample.rxbus.Subscribe;
import com.github.florent37.camerafragment.sample.rxbus.ThreadMode;
import com.github.florent37.camerafragment.sample.slice.CameraFragmentAbilityCustomsSlice;

/**
 * 相机另一布局
 *
 * @since 2021-03-17
 */
public class CameraFragmentAbilityCustoms extends FractionAbility {
    private static final int REQUEST_CAMERA_PERMISSIONS = 931;
    private CameraFragmentAbilityCustomsSlice slice;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setMainRoute(CameraFragmentAbilityCustomsSlice.class.getName());
        RxBus.get(this).register(this); // 注册RxBus
    }

    @Override
    public void onRequestPermissionsFromUserResult(int requestCode, String[] permissions, int[] grantResults) {
        if (requestCode == REQUEST_CAMERA_PERMISSIONS) { // 匹配requestPermissions的requestCode
            int canOpenCamera = 0;
            for (int ii = 0; ii < grantResults.length; ii++) {
                if (grantResults[ii] == IBundleManager.PERMISSION_GRANTED) {
                    canOpenCamera++;
                }
            }
            if (grantResults.length > 0 && canOpenCamera == grantResults.length) {
                // 权限被授予
                // 注意：因时间差导致接口权限检查时有无权限，所以对那些因无权限而抛异常的接口进行异常捕获处理
                if (slice != null) {
                    slice.addCamera();
                    RxBus.get(this).unRegister(this); // 注销rxbus
                }
            } else {
                // 权限被拒绝
                Toast.show(getContext(), "权限授予失败,请前往设置授权");
            }
        }
    }

    /**
     * 接收事件
     *
     * @param rxbusEvent 接受参数
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void rxBusCustomsEvent(RxBusEvent rxbusEvent) {
        if (rxbusEvent == null) {
            return;
        }
        slice = (CameraFragmentAbilityCustomsSlice) rxbusEvent.getAbility(); // 执行对应操作
    }
}
